using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaUI.Modal.Controls;

namespace AvaloniaUI.Modal.Services
{
    /// <summary>
    /// 模态对话框服务，负责显示和关闭模态对话框
    /// </summary>
    public class ModalService : IModalService
    {
        // 使用弱引用存储ModalHost实例，避免内存泄漏
        private readonly Dictionary<string, WeakReference<ModalHost>> _hostRegistry = new();
        
        // 缓存视觉根元素到ModalHost的映射
        private readonly Dictionary<Control, WeakReference<ModalHost>> _rootToHostCache = new();
        
        // 缓存最近使用的ModalHost
        private ModalHost _lastUsedHost;
        
        // 默认ModalHost的ID
        private string _defaultHostId;
        
        // 定期清理计时器
        private DispatcherTimer _cleanupTimer;
        
        private static ModalService _instance;

        /// <summary>
        /// 获取模态对话框服务的单例实例
        /// </summary>
        public static ModalService Instance => _instance ??= new ModalService();
        
        /// <summary>
        /// 初始化ModalService类的新实例
        /// </summary>
        private ModalService()
        {
            // 设置定期清理计时器
            _cleanupTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMinutes(10) // 每10分钟清理一次
            };
            
            _cleanupTimer.Tick += (sender, e) => CleanupInvalidReferences();
            _cleanupTimer.Start();
        }

        /// <summary>
        /// 异步显示模态对话框
        /// </summary>
        /// <typeparam name="TResult">结果类型</typeparam>
        /// <param name="content">对话框内容（通常是ViewModel）</param>
        /// <returns>对话框结果</returns>
        public Task<TResult> ShowDialogAsync<TResult>(object content)
        {
            return ShowDialogAsync<TResult>(content, new ModalDialogOptions(), null);
        }

        /// <summary>
        /// 异步显示模态对话框，并指定选项
        /// </summary>
        /// <typeparam name="TResult">结果类型</typeparam>
        /// <param name="content">对话框内容（通常是ViewModel）</param>
        /// <param name="options">对话框选项</param>
        /// <returns>对话框结果</returns>
        public Task<TResult> ShowDialogAsync<TResult>(object content, ModalDialogOptions options)
        {
            return ShowDialogAsync<TResult>(content, options, null);
        }
        
        /// <summary>
        /// 使用指定ID的ModalHost显示对话框
        /// </summary>
        /// <typeparam name="TResult">结果类型</typeparam>
        /// <param name="content">对话框内容（通常是ViewModel）</param>
        /// <param name="hostId">ModalHost的ID</param>
        /// <returns>对话框结果</returns>
        public Task<TResult> ShowDialogAsync<TResult>(object content, string hostId)
        {
            return ShowDialogAsync<TResult>(content, new ModalDialogOptions(), hostId);
        }
        
        /// <summary>
        /// 使用指定ID的ModalHost显示对话框，并指定选项
        /// </summary>
        /// <typeparam name="TResult">结果类型</typeparam>
        /// <param name="content">对话框内容（通常是ViewModel）</param>
        /// <param name="options">对话框选项</param>
        /// <param name="hostId">ModalHost的ID</param>
        /// <returns>对话框结果</returns>
        public Task<TResult> ShowDialogAsync<TResult>(object content, ModalDialogOptions options, string hostId)
        {
            var host = GetModalHost(hostId);
            if (host == null)
            {
                throw new InvalidOperationException(
                    string.IsNullOrEmpty(hostId)
                        ? "无法找到模态对话框宿主控件。请确保在XAML中添加了ModalHost控件，或者应用程序具有有效的视觉根元素。"
                        : $"无法找到ID为'{hostId}'的模态对话框宿主控件。");
            }

            host.Content = content;
            host.OverlayBrush = options.OverlayBrush ?? host.OverlayBrush;
            host.CloseOnClickOverlay = options.CloseOnClickOverlay;
            host.CloseOnEscape = options.CloseOnEscape;
            host.Animation = options.Animation;

            return host.ShowAsync<TResult>();
        }

        /// <summary>
        /// 关闭当前对话框
        /// </summary>
        /// <param name="result">对话框结果</param>
        public void CloseDialog(object result = null)
        {
            var host = GetCurrentModalHost();
            if (host != null)
            {
                host.Close(result);
            }
        }

        /// <summary>
        /// 关闭所有对话框
        /// </summary>
        public void CloseAll()
        {
            // 获取所有有效的ModalHost实例
            var hostsToClose = new List<ModalHost>();
            
            foreach (var pair in _hostRegistry)
            {
                if (pair.Value.TryGetTarget(out var host))
                {
                    hostsToClose.Add(host);
                }
            }
            
            // 关闭所有对话框
            foreach (var host in hostsToClose)
            {
                host.Close(null);
            }
        }

        /// <summary>
        /// 注册一个ModalHost实例
        /// </summary>
        /// <param name="hostId">ModalHost的ID</param>
        /// <param name="host">要注册的ModalHost实例</param>
        /// <param name="isDefault">是否为默认ModalHost</param>
        internal void RegisterHost(string hostId, ModalHost host, bool isDefault)
        {
            if (string.IsNullOrEmpty(hostId))
            {
                hostId = Guid.NewGuid().ToString();
            }
            
            // 获取ModalHost所在的窗口
            var window = host.GetVisualRoot() as Window;
            if (window != null)
            {
                // 将窗口信息添加到hostId中，确保在不同窗口中的相同hostId不会冲突
                var fullHostId = $"{window.GetHashCode()}:{hostId}";
                _hostRegistry[fullHostId] = new WeakReference<ModalHost>(host);
                
                // 注册窗口关闭事件
                RegisterWindowEvents(window);
                
                // 如果是默认ModalHost，更新默认ID和缓存
                if (isDefault)
                {
                    _defaultHostId = fullHostId;
                    _rootToHostCache[window as Control] = new WeakReference<ModalHost>(host);
                }
            }
            else
            {
                // 如果找不到窗口，直接使用hostId
                _hostRegistry[hostId] = new WeakReference<ModalHost>(host);
                
                if (isDefault)
                {
                    _defaultHostId = hostId;
                    
                    // 尝试获取视觉根元素
                    var root = host.GetVisualRoot();
                    if (root != null)
                    {
                        if (root is Control controlRoot)
                        {
                            _rootToHostCache[controlRoot] = new WeakReference<ModalHost>(host);
                        }
                    }
                }
            }
            
            // 更新最近使用的ModalHost
            _lastUsedHost = host;
        }
        
        /// <summary>
        /// 注销一个ModalHost实例
        /// </summary>
        /// <param name="hostId">ModalHost的ID</param>
        internal void UnregisterHost(string hostId)
        {
            if (string.IsNullOrEmpty(hostId))
                return;
                
            // 尝试查找包含窗口信息的完整hostId
            var keysToRemove = new List<string>();
            foreach (var key in _hostRegistry.Keys)
            {
                if (key.EndsWith($":{hostId}") || key == hostId)
                {
                    keysToRemove.Add(key);
                    
                    // 如果是默认ModalHost，清除默认ID
                    if (_defaultHostId == key)
                    {
                        _defaultHostId = null;
                    }
                }
            }
            
            // 移除所有匹配的项
            foreach (var key in keysToRemove)
            {
                _hostRegistry.Remove(key);
            }
            
            // 清理rootToHostCache中的无效引用
            var rootsToRemove = new List<Control>();
            foreach (var pair in _rootToHostCache)
            {
                if (!pair.Value.TryGetTarget(out var host) ||
                    host.HostId == hostId ||
                    !host.IsAttachedToVisualTree())
                {
                    rootsToRemove.Add(pair.Key);
                }
            }
            
            foreach (var root in rootsToRemove)
            {
                _rootToHostCache.Remove(root);
            }
            
            // 如果是最近使用的ModalHost，清除引用
            if (_lastUsedHost != null && _lastUsedHost.HostId == hostId)
            {
                _lastUsedHost = null;
            }
        }
        
        /// <summary>
        /// 注册窗口事件
        /// </summary>
        /// <param name="window">要注册事件的窗口</param>
        private void RegisterWindowEvents(Window window)
        {
            if (window != null)
            {
                // 避免重复注册
                window.Closed -= Window_Closed;
                window.Closed += Window_Closed;
            }
        }
        
        /// <summary>
        /// 窗口关闭事件处理
        /// </summary>
        private void Window_Closed(object sender, EventArgs e)
        {
            if (sender is Window window)
            {
                // 清理该窗口的缓存
                _rootToHostCache.Remove(window);
                
                // 清理包含该窗口信息的hostId
                var windowHashCode = window.GetHashCode();
                var keysToRemove = new List<string>();
                
                foreach (var key in _hostRegistry.Keys)
                {
                    if (key.StartsWith($"{windowHashCode}:"))
                    {
                        keysToRemove.Add(key);
                        
                        // 如果是默认ModalHost，清除默认ID
                        if (_defaultHostId == key)
                        {
                            _defaultHostId = null;
                        }
                    }
                }
                
                foreach (var key in keysToRemove)
                {
                    _hostRegistry.Remove(key);
                }
                
                // 取消事件订阅
                window.Closed -= Window_Closed;
            }
        }
        
        /// <summary>
        /// 清理无效引用
        /// </summary>
        private void CleanupInvalidReferences()
        {
            // 清理_hostRegistry中的无效引用
            var invalidHostIds = new List<string>();
            foreach (var pair in _hostRegistry)
            {
                if (!pair.Value.TryGetTarget(out var host) || !host.IsAttachedToVisualTree())
                {
                    invalidHostIds.Add(pair.Key);
                }
            }
            
            foreach (var hostId in invalidHostIds)
            {
                _hostRegistry.Remove(hostId);
                
                // 如果是默认ModalHost，清除默认ID
                if (_defaultHostId == hostId)
                {
                    _defaultHostId = null;
                }
            }
            
            // 清理_rootToHostCache中的无效引用
            var invalidRoots = new List<Control>();
            foreach (var pair in _rootToHostCache)
            {
                if (!pair.Value.TryGetTarget(out var host) || !host.IsAttachedToVisualTree())
                {
                    invalidRoots.Add(pair.Key);
                }
            }
            
            foreach (var root in invalidRoots)
            {
                _rootToHostCache.Remove(root);
            }
        }

        /// <summary>
        /// 获取ModalHost
        /// </summary>
        /// <param name="hostId">ModalHost的ID，如果为null则获取默认ModalHost</param>
        /// <returns>找到的ModalHost，如果不存在则返回null</returns>
        private ModalHost GetModalHost(string hostId = null)
        {
            // 获取当前窗口
            var currentRoot = GetVisualRoot();
            
            // 1. 如果指定了hostId，从注册表中查找
            if (!string.IsNullOrEmpty(hostId))
            {
                ModalHost foundHost = null;
                
                // 尝试查找包含窗口信息的完整hostId
                if (currentRoot is Window window)
                {
                    var fullHostId = $"{window.GetHashCode()}:{hostId}";
                    if (_hostRegistry.TryGetValue(fullHostId, out var windowHostRef) &&
                        windowHostRef.TryGetTarget(out var windowHost) &&
                        windowHost.IsAttachedToVisualTree())
                    {
                        foundHost = windowHost;
                    }
                }
                
                // 如果没找到，尝试直接查找hostId
                if (foundHost == null && _hostRegistry.TryGetValue(hostId, out var directHostRef) &&
                    directHostRef.TryGetTarget(out var directHost) &&
                    directHost.IsAttachedToVisualTree())
                {
                    foundHost = directHost;
                }
                
                if (foundHost != null)
                {
                    _lastUsedHost = foundHost;
                    return foundHost;
                }
            }
            
            // 2. 如果没有指定hostId或者没有找到，尝试使用默认ModalHost
            var defaultHost = GetDefaultModalHost();
            if (defaultHost != null)
            {
                _lastUsedHost = defaultHost;
                return defaultHost;
            }
            
            // 3. 如果还没找到，尝试使用最近使用的ModalHost
            if (_lastUsedHost != null && _lastUsedHost.IsAttachedToVisualTree())
            {
                return _lastUsedHost;
            }
            
            // 4. 如果还没找到，尝试从缓存中查找
            if (currentRoot != null && _rootToHostCache.TryGetValue(currentRoot, out var cachedHostRef))
            {
                if (cachedHostRef.TryGetTarget(out var cachedHost) && cachedHost.IsAttachedToVisualTree())
                {
                    _lastUsedHost = cachedHost;
                    return cachedHost;
                }
                else
                {
                    // 清理无效引用
                    _rootToHostCache.Remove(currentRoot);
                }
            }
            
            // 5. 如果还没找到，尝试从视觉树中查找
            if (currentRoot != null)
            {
                var host = FindModalHostInVisualTree(currentRoot);
                if (host != null)
                {
                    // 更新缓存
                    _rootToHostCache[currentRoot] = new WeakReference<ModalHost>(host);
                    _lastUsedHost = host;
                    return host;
                }
            }
            
            return null;
        }
        
        /// <summary>
        /// 获取默认ModalHost
        /// </summary>
        /// <returns>默认ModalHost，如果不存在则返回null</returns>
        private ModalHost GetDefaultModalHost()
        {
            // 如果有默认ModalHost，尝试获取
            ModalHost defaultHost = null;
            if (!string.IsNullOrEmpty(_defaultHostId) &&
                _hostRegistry.TryGetValue(_defaultHostId, out var defaultHostRef) &&
                defaultHostRef.TryGetTarget(out defaultHost) &&
                defaultHost.IsAttachedToVisualTree())
            {
                return defaultHost;
            }
            
            // 如果没有默认ModalHost，尝试从视觉树中查找IsDefault=true的ModalHost
            var root = GetVisualRoot();
            if (root != null)
            {
                var host = FindDefaultModalHostInVisualTree(root);
                if (host != null)
                {
                    // 更新默认ModalHost
                    _defaultHostId = host.HostId;
                    _rootToHostCache[root] = new WeakReference<ModalHost>(host);
                    return host;
                }
            }
            
            return null;
        }
        
        /// <summary>
        /// 在视觉树中查找ModalHost
        /// </summary>
        /// <param name="root">视觉根元素</param>
        /// <returns>找到的ModalHost，如果不存在则返回null</returns>
        private ModalHost FindModalHostInVisualTree(Control root)
        {
            // 如果当前控件是ModalHost，返回它
            if (root is ModalHost modalHost)
            {
                return modalHost;
            }
            
            // 递归查找子控件
            foreach (var child in root.GetVisualChildren())
            {
                if (child is Control control)
                {
                    var result = FindModalHostInVisualTree(control);
                    if (result != null)
                    {
                        return result;
                    }
                }
            }
            
            return null;
        }
        
        /// <summary>
        /// 在视觉树中查找默认ModalHost
        /// </summary>
        /// <param name="root">视觉根元素</param>
        /// <returns>找到的默认ModalHost，如果不存在则返回null</returns>
        private ModalHost FindDefaultModalHostInVisualTree(Control root)
        {
            // 如果当前控件是ModalHost且IsDefault=true，返回它
            if (root is ModalHost modalHost && modalHost.IsDefault)
            {
                return modalHost;
            }
            
            // 递归查找子控件
            foreach (var child in root.GetVisualChildren())
            {
                if (child is Control control)
                {
                    var result = FindDefaultModalHostInVisualTree(control);
                    if (result != null)
                    {
                        return result;
                    }
                }
            }
            
            return null;
        }

        /// <summary>
        /// 获取当前的ModalHost（用于关闭对话框）
        /// </summary>
        /// <returns>当前的ModalHost，如果不存在则返回null</returns>
        private ModalHost GetCurrentModalHost()
        {
            // 优先使用最近使用的ModalHost
            if (_lastUsedHost != null && _lastUsedHost.IsAttachedToVisualTree())
            {
                return _lastUsedHost;
            }
            
            // 如果没有最近使用的ModalHost，尝试获取默认ModalHost
            return GetModalHost();
        }

        /// <summary>
        /// 获取当前应用程序的视觉根元素
        /// </summary>
        /// <returns>视觉根元素，如果找不到则返回null</returns>
        private Control GetVisualRoot()
        {
            // 检查Application.Current是否存在
            if (Application.Current == null)
                return null;

            // 检查ApplicationLifetime类型
            var lifetime = Application.Current.ApplicationLifetime;

            // 处理传统桌面应用
            if (lifetime is IClassicDesktopStyleApplicationLifetime desktop)
            {
                return desktop.MainWindow;
            }

            // 处理单视图应用（如移动应用）
            if (lifetime is ISingleViewApplicationLifetime singleView)
            {
                return singleView.MainView;
            }

            // 尝试通过Application.Current.Windows获取活动窗口
            if (Application.Current != null)
            {
                // 在某些Avalonia版本中，可以通过Application.Current.Windows获取所有窗口
                var windowsProperty = typeof(Application).GetProperty("Windows");
                if (windowsProperty != null)
                {
                    var windows = windowsProperty.GetValue(Application.Current) as IEnumerable<Window>;
                    if (windows != null && windows.Any())
                    {
                        return windows.FirstOrDefault(w => w.IsActive) ?? windows.FirstOrDefault();
                    }
                }
            }

            // 如果无法获取窗口，返回null
            return null;
        }
    }
}